package com.tony.ai.camerax

import android.annotation.SuppressLint
import android.content.ContentValues
import android.content.Context
import android.graphics.Bitmap
import android.provider.MediaStore
import android.util.Log
import android.view.GestureDetector
import android.view.MotionEvent
import android.widget.Toast
import androidx.camera.core.*
import androidx.camera.core.impl.ImageAnalysisConfig
import androidx.camera.core.impl.VideoCaptureConfig
import androidx.camera.lifecycle.ProcessCameraProvider
import androidx.camera.view.PreviewView
import androidx.core.content.ContextCompat
import androidx.fragment.app.FragmentActivity
import androidx.lifecycle.LifecycleOwner
import com.google.common.util.concurrent.ListenableFuture
import com.tony.ai.ai.TextRecognitionHelper
import com.tony.ai.ai.analyzer.TextAnalyzer
import java.io.File
import java.lang.Exception
import java.util.concurrent.ExecutorService
import java.util.concurrent.Executors


/**
 * CameraX帮助类
 */
class CameraPreviewUtil(
    var context: Context,
    var viewFinder: PreviewView,
    var lifecycleOwner: FragmentActivity
) {
    enum class AnalyzerType {
        SEGMENTATION,
        TEXT
    }

    private val TAG = "CameraXHelper"
    private val ZOOM_SENSITIVITY = 0.1f
    private var cameraProviderFuture: ListenableFuture<ProcessCameraProvider>? = null
    private var camera: Camera? = null
    private var imageAnalyzer: ImageAnalysis? = null
    private var cameraExecutor: ExecutorService? = null
    private var bitmapBuffer: Bitmap? = null
    private var cameraProvider: ProcessCameraProvider? = null

    init {
        cameraExecutor = Executors.newSingleThreadExecutor()
        cameraProviderFuture = ProcessCameraProvider.getInstance(context)
    }


    private fun getPreview(): Preview {
        return Preview.Builder()
            .setTargetAspectRatio(AspectRatio.RATIO_4_3)
            .setTargetRotation(viewFinder.display.rotation)
            .build()
    }

    /**
     * 设置目标旋转角度
     */
    fun setTargetRotation(viewFinder: PreviewView) {
        imageAnalyzer?.targetRotation = viewFinder.display.rotation
    }

    @SuppressLint("UnsafeExperimentalUsageError")
    private fun bindImageAnalyzer(resultListener: OnImageAnalysisResultListener) {
        imageAnalyzer = ImageAnalysis.Builder()
            .setTargetAspectRatio(AspectRatio.RATIO_4_3)
            .setTargetRotation(viewFinder.display.rotation)
            .setBackpressureStrategy(ImageAnalysis.STRATEGY_KEEP_ONLY_LATEST)
//            .setOutputImageFormat(OUTPUT_IMAGE_FORMAT_RGBA_8888)
            .build()
            // The analyzer can then be assigned to the instance
            .also {
                it.setAnalyzer(cameraExecutor!!) { image ->
//                    if (!::bitmapBuffer.isInitialized) {
//                        // The image rotation and RGB image buffer are initialized only once
//                        // the analyzer has started running
//                        bitmapBuffer = Bitmap.createBitmap(
//                            image.width,
//                            image.height,
//                            Bitmap.Config.ARGB_8888
//                        )
//                    }
//                    bitmapBuffer.copyPixelsFromBuffer(image.planes[0].buffer)
                    val imageRotation = image.imageInfo.rotationDegrees
                    resultListener.onImageAnalysisResult(image)
                    bitmapBuffer = ImageUtils.imageProxyToBitmap(image)
                    Log.e(TAG, "image.width:${image.width},image.height:${image.height}")
                    resultListener.onBitmapRotation(bitmapBuffer, imageRotation)
                    image.close()
                }
            }
    }

    @SuppressLint("UnsafeExperimentalUsageError")
    private fun bindTextAnalyzer(resultListener: OnImageAnalysisResultListener) {
        imageAnalyzer = ImageAnalysis.Builder()
            .setTargetAspectRatio(AspectRatio.RATIO_4_3)
            .setTargetRotation(viewFinder.display.rotation)
            .setBackpressureStrategy(ImageAnalysis.STRATEGY_KEEP_ONLY_LATEST)
//            .setOutputImageFormat(OUTPUT_IMAGE_FORMAT_RGBA_8888)
            .build().also {
                it.setAnalyzer(
                    cameraExecutor!!,
                    TextAnalyzer(TextRecognitionHelper.imageCropPercentages) { image, mCroppedBitmap ->
                        val imageRotation = image.imageInfo.rotationDegrees
                        resultListener.onImageAnalysisResult(image)
//                        bitmapBuffer = ImageUtils.imageProxyToBitmap(image)
                        Log.e(
                            TAG,
                            "image.width:${mCroppedBitmap.width},image.height:${mCroppedBitmap.height}"
                        )
                        resultListener.onBitmapRotation(mCroppedBitmap, imageRotation)
                    })
            }

        // The analyzer can then be assigned to the instance
//            .also {
//                it.setAnalyzer(cameraExecutor!!) { image ->
//                    val imageRotation = image.imageInfo.rotationDegrees
//                    resultListener.onImageAnalysisResult(image)
//                    bitmapBuffer = ImageUtils.imageProxyToBitmap(image)
//                    Log.e(TAG,"image.width:${image.width},image.height:${image.height}")
//                    resultListener.onBitmapRotation(bitmapBuffer, imageRotation)
//                    image.close()
//                }
//    }
    }

    /**
     * 开始预览
     */
    fun startPreview(type: AnalyzerType, resultListener: OnImageAnalysisResultListener) {
        if (viewFinder.display != null) {
            Log.e(TAG, "ViewFinder不等于null")
        } else {
            Log.e(TAG, "ViewFinder等于null")
        }
        //添加一个监听方法
        cameraProviderFuture?.addListener({
            //创建CameraProvider
            cameraProvider = cameraProviderFuture?.get()!!
            val preview = getPreview()
            when (type) {
                AnalyzerType.TEXT -> {
                    bindTextAnalyzer(resultListener)
                }

                else -> {
                    bindImageAnalyzer(resultListener)
                }
            }

            //接触所有绑定相当于重置
            cameraProvider?.unbindAll()
            //给Preview绑定生命周期
            camera = cameraProvider?.bindToLifecycle(
                lifecycleOwner,
                CameraSelector.DEFAULT_BACK_CAMERA,
                preview, imageAnalyzer
            )
            //得到CameraInfo，并把preview和PreviewView绑定，用于用于展示预览结果（非常重要）
            val cameraInfo = camera!!.cameraInfo
//            preview.setSurfaceProvider(viewFinder.createSurfaceProvider(cameraInfo))
            preview.setSurfaceProvider(viewFinder.surfaceProvider)
            val cameraControl = camera!!.cameraControl
//            addGestureDetector(cameraInfo, cameraControl)
        }, ContextCompat.getMainExecutor(context))
    }

    fun stopPreview() {
        try {
            cameraProvider?.unbindAll()
            if (!cameraProviderFuture?.isCancelled!!) {
                cameraProviderFuture?.cancel(true)
            }
            onDestroy()
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }


    private fun onDestroy() {
        cameraExecutor?.shutdown()
    }

    interface OnImageAnalysisResultListener {
        fun onImageAnalysisResult(image: ImageProxy) {}
        fun onBitmapRotation(bitmap: Bitmap?, rotation: Int) {}
    }

}